package com.wonders.frame.chron.controller.card;

import com.wonders.frame.chron.controller.BasicChronController;
import com.wonders.frame.chron.dao.card.CardDao;
import com.wonders.frame.chron.model.bo.Card;
import com.wonders.frame.chron.model.bo.Catalog;
import com.wonders.frame.chron.model.vo.CatalogVo;
import com.wonders.frame.chron.service.catalog.CatalogService;
import com.wonders.frame.chron.util.FreeMarkerUtils;
import com.wonders.frame.chron.util.LoginConstants;
import com.wonders.frame.chron.util.StringUtil;
import com.wonders.frame.core.model.IDefaultModel;
import com.wonders.frame.core.model.vo.RelatedNode;
import com.wonders.frame.core.model.vo.ReturnObj;
import com.wonders.frame.core.model.vo.SingleModelParams;
import com.wonders.frame.core.model.vo.SingleQueryParams;
import com.wonders.frame.core.utils.ReflectUtil;
import com.wonders.frame.core.utils.SingleParamsConvertUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//import sun.misc.BASE64Encoder;

@Controller
@RequestMapping("/card")
public class CardController extends BasicChronController<Card> {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private CatalogService catalogService;

	/**
	 * 导出多张卡片
	 * @param id
	 * @param type
	 * @param sortField
	 * @param sortAsc
	 * @param neededObj
	 * @param lv
	 * @param ticket
	 * @param resourceType
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/exportCards/{ids}")
	@ResponseBody
	public String exportCards(
			@PathVariable("ids") String id,
			@RequestParam(value = "type", required = false, defaultValue = "") String type,
			@RequestParam(value = "sortField", required = false, defaultValue = "") String sortField,
			@RequestParam(value = "sortAsc", required = false, defaultValue = "asc") String sortAsc,
			@RequestParam(value = "objFilter", required = false, defaultValue = "") String neededObj,
			@RequestParam(value = "lv", required = false, defaultValue = "-1") int lv,
			@RequestParam(value = "ticket", required = true) String ticket,
			@RequestParam(value = "resourceType", required = true) String resourceType,
			HttpServletRequest request, HttpServletResponse response){

		String catalogType=this.getEntityName();
		/** 模板引擎所需要的数据Map */
		Map<String, Object> templateData = new HashMap<String, Object>();
		// 查询该卡片的父级节点
		SingleQueryParams sqp = SingleParamsConvertUtil.getQueryParams(this.getEntityClass(), request);
		sqp.addSort("operateTime", "asc");
		sqp.addData("id_in", id);
		ReturnObj<List<IDefaultModel>> returnObj = getBasicCrudService().find(sqp);
		if (!returnObj.getInfo().getSuccess()) 
			return null;
		List<CatalogVo> catalogVos=new ArrayList<CatalogVo>();
		
		for (IDefaultModel data : returnObj.getData()) {
			Card c=(Card) data;
			//查询该卡片父节点
			ReturnObj<List<RelatedNode<IDefaultModel, Integer>>> parentNode = getParentNode(c.getId(), sortField, sortAsc, neededObj, 1, ticket);
	
			if (!parentNode.getInfo().getSuccess()) 
					continue;
			
			CatalogVo vo=new CatalogVo();
			//得到卡片
			vo.setCard(c);
			vo.setCatalog((Catalog)parentNode.getData().get(0).getNode());
			catalogVos.add(vo);
		}
		List<Map<String, Object>> catalogList =  catalogService.getCatalogs(sortField, sortAsc,
				neededObj, lv, ticket, resourceType,catalogType);
		templateData.put("catalogs", catalogList);
		templateData.put("catalogVos", catalogVos);
		templateData.put("title", "卡片");
		// 初始化模板引擎
		FreeMarkerUtils.initFreeMarker(request.getSession().getServletContext().getRealPath("/"), response,"上海申通地铁集团修志卡片文档");
		Writer out;
		try {
			// 重点：一定要注意编码格式，漏写编码格式将导致word无法打开（xml非法字符）
			out = new BufferedWriter(new OutputStreamWriter(
					response.getOutputStream(), "utf-8"));
			FreeMarkerUtils.createDoc(templateData, out, "templates/catalog-cards-mht.ftl");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}

	/***
	 * 导出单张卡片
	 * @param id
	 * @param type
	 * @param sortField
	 * @param sortAsc
	 * @param neededObj
	 * @param ticket
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/exportCard")
	@ResponseBody
	public String exportCard(
			@RequestParam("id") Integer id,
			@RequestParam(value = "type", required = false, defaultValue = "") String type,
			@RequestParam(value = "sortField", required = false, defaultValue = "") String sortField,
			@RequestParam(value = "sortAsc", required = false, defaultValue = "asc") String sortAsc,
			@RequestParam(value = "objFilter", required = false, defaultValue = "") String neededObj,
			@RequestParam(value = "ticket", required = true) String ticket,
			HttpServletRequest request, HttpServletResponse response){

		/** 模板引擎所需要的数据Map */
		Map<String, Object> templateData = new HashMap<String, Object>();
		
		ReturnObj<List<RelatedNode<IDefaultModel,Integer>>> node = getParentNode(id, sortField, sortAsc, neededObj, 1, ticket);
		
		if (node.getInfo().getSuccess()) {
		
			CatalogVo vo=new CatalogVo();
			//得到卡片
			Card card = get(id+"");
			
			vo.setCard(card);
			
			vo.setCatalog((Catalog)node.getData().get(0).getNode());

			templateData.put("vo",vo);
			templateData.put("title","卡片");
			FreeMarkerUtils.initFreeMarker(request.getSession().getServletContext().getRealPath("/"), response,card.getCardNo());

			// 重点：一定要注意编码格式，漏写编码格式将导致word无法打开（xml非法字符）
			Writer out;
			try {
				out = new BufferedWriter(new OutputStreamWriter(
						response.getOutputStream(), "utf-8"));
				FreeMarkerUtils.createDoc(templateData, out, "templates/card-mht.ftl");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	/**
	 * 导出全部卡片
	 * @param id 目录ID
	 * @param type
	 * @param sortField
	 * @param sortAsc
	 * @param neededObj
	 * @param lv
	 * @param ticket
	 * @param resourceType
	 * @param request
	 * @param response
	 * @param idList 
	 * @return
	 */
	@RequestMapping("/exportAll")
	@ResponseBody
	public String exportAll(
					@RequestParam("ids") String ids,
					@RequestParam(value = "type", required = false, defaultValue = "") String type,
					@RequestParam(value = "sortField", required = false, defaultValue = "") String sortField,
					@RequestParam(value = "sortAsc", required = false, defaultValue = "asc") String sortAsc,
					@RequestParam(value = "objFilter", required = false, defaultValue = "") String neededObj,
					@RequestParam(value = "lv", required = false, defaultValue = "-1") int lv,
					@RequestParam(value = "ticket", required = true) String ticket,
					@RequestParam(value = "resourceType", required = true) String resourceType,
					HttpServletRequest request, HttpServletResponse response){

		String catalogType=this.getEntityName();
		List<Integer> catalogIds=new ArrayList<Integer>();
		for (String id : StringUtils.split(ids,",")) {
			catalogIds.add(Integer.parseInt(id));
		}
		String cardIds = (String)ReflectUtil.executeMethod("catalog", "findByCardsOrSummarys", 
                new Class[] { List.class, String.class, String.class }, new Object[] { catalogIds, "catalog", catalogType});

		/** 模板引擎所需要的数据Map */
		Map<String, Object> templateData = new HashMap<String, Object>();
		if (!StringUtil.isNull(cardIds)) {
			SingleQueryParams sqp = SingleParamsConvertUtil.getQueryParams(this.getEntityClass(), request);
			sqp.addSort("operateTime", "asc");
			sqp.addData("status", "finish");
			sqp.addData("id_in", cardIds);
			ReturnObj<List<IDefaultModel>> returnObj = getBasicCrudService().find(sqp);
			if (!returnObj.getInfo().getSuccess()) 
				return null;
			
			List<CatalogVo> catalogVos=new ArrayList<CatalogVo>();
			
			for (IDefaultModel data : returnObj.getData()) {
				Card c=(Card) data;
				//查询该卡片父节点
				ReturnObj<List<RelatedNode<IDefaultModel, Integer>>> parentNode = getParentNode(c.getId(), sortField, sortAsc, neededObj, 1, ticket);
		
				if (!parentNode.getInfo().getSuccess()) 
						continue;
				
				CatalogVo vo=new CatalogVo();
				//得到卡片
				vo.setCard(c);
				vo.setCatalog((Catalog)parentNode.getData().get(0).getNode());
				catalogVos.add(vo);
			}
			List<Map<String, Object>> catalogList = catalogService.getCatalogs(sortField,
					sortAsc, neededObj, lv, ticket, resourceType,catalogType);
			templateData.put("catalogs", catalogList);
			templateData.put("catalogVos", catalogVos);
			templateData.put("title", "卡片");
			// 初始化模板引擎
			FreeMarkerUtils.initFreeMarker(request.getSession().getServletContext().getRealPath("/"), response,"上海申通地铁集团修志卡片文档");
			Writer out;
			try {
				// 重点：一定要注意编码格式，漏写编码格式将导致word无法打开（xml非法字符）
				out = new BufferedWriter(new OutputStreamWriter(
						response.getOutputStream(), "utf-8"));
				FreeMarkerUtils.createDoc(templateData, out, "templates/catalog-cards-mht.ftl");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@RequestMapping(value = "/rebindCatalog", method = RequestMethod.POST)
	@ResponseBody
	public int rebindCatalog(HttpServletRequest request){
		String pIdNew = request.getParameter("pIdNew");
		String cardIds = request.getParameter("cardIds");
		String code = request.getParameter("code");
		
		List<Integer> cardIdList = new ArrayList<Integer>();
		for(String cardId : StringUtils.split(cardIds, ",")){
			cardIdList.add(Integer.valueOf(cardId));
		}
		
		return cardDao.rebindCatalog(Integer.valueOf(pIdNew), cardIdList, code);
	}
	
	@RequestMapping(value = "/getSerial", method = RequestMethod.GET)
	@ResponseBody
	public String getSerial(HttpSession session){
		return cardDao.getSerialNo((String)session.getAttribute(LoginConstants.DEPTID));
	}
	
	@RequestMapping(value = "/bindSummary", method = RequestMethod.POST)
	@ResponseBody
	public int bindSummary(HttpServletRequest request){
		String summaryId = request.getParameter("summaryId");
		String cardIds = request.getParameter("cardIds");
		
		List<Integer> cardIdList = new ArrayList<Integer>();
		for(String cardId : StringUtils.split(cardIds, ",")){
			cardIdList.add(Integer.valueOf(cardId));
		}
		
		return cardDao.bindSummary(Integer.valueOf(summaryId), cardIdList);
	}
	
	@RequestMapping(value = "/unbindSummary", method = RequestMethod.POST)
	@ResponseBody
	public int unbindSummary(HttpServletRequest request){
		String summaryId = request.getParameter("summaryId");
		return cardDao.unbindSummary(Integer.valueOf(summaryId));
	}	
	
	public void addExtraOnSave(HttpServletRequest request, SingleModelParams smp){
		smp.addData("cardNo", this.cardDao.getSerialNo((String)request.getSession().getAttribute(LoginConstants.DEPTID)));
	}
	
	@Autowired
	CardDao cardDao;
}
